import { Component, OnInit } from '@angular/core';
import {CamType} from "../../shared/model/camType";
import {CamTypeService} from "../../shared/service/cam-type.service";
import {Router} from "@angular/router";

@Component({
  selector: 'app-type-list',
  templateUrl: './type-list.component.html',
  styleUrls: ['./type-list.component.css']
})
export class TypeListComponent implements OnInit {
  types:CamType[];
  oldTypes:CamType[];
  selectedType:CamType;
  constructor(private camTypeService:CamTypeService,private router:Router) { }

  ngOnInit() {
    this.getTypes();
    this.camTypeService.searchEvent.subscribe(
      param => {
        let result = this.oldTypes;
        if (param) {
          result = result.filter((f: CamType) => f.name.indexOf(param) !== -1);
        }
        this.types = result;
      }
    );
    this.camTypeService.listFreshEvent.subscribe(
      param => {
        if (param) {
          this.camTypeService.searchFreshEvent.emit("reset");
          this.getTypes();
        }
      }
    );
  }

  getTypes(){
    this.camTypeService.getTypes().then(
      res => {
        this.types = res;
        this.oldTypes = res;
      }
    );
  }

  onSelect(type: CamType): void {
    this.selectedType = type;
  }

  delType(type: CamType):void {
    if(confirm("确认删除?")){
      this.camTypeService.deleteType(type.oid).then(
        res => {
          alert(res.message);
          this.camTypeService.searchFreshEvent.emit("reset");
          this.router.navigateByUrl('/camType/new');
          this.getTypes();
        }
      )
    }
  }

}
